<?php

namespace app\admin\controller\facrm;

use app\common\controller\Backend;
use app\common\model\Config;
use think\Db;

/**
 * 自定义字段
 *
 * @icon fa fa-circle-o
 */
class Fields extends Backend
{

    /**
     * Fields模型对象
     */
    protected $model = null;
    protected $modelValidate = true;
    protected $modelSceneValidate = true;

    protected $noNeedRight = ['get_fields_html', 'rulelist', 'getTableFields','selectpage'];
    protected $multiFields = 'isfilter,islist';

    private $modelList = array();

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\facrm\Fields;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign('typeList', Config::getTypeList());
        $this->view->assign('regexList', Config::getRegexList());
        $this->modelList = ['customer' => __('客户'), 'customer_contacts' => __('联系人'),'contract'=>__("合同"),'contract_receivables'=>__("回款"),'business'=>__("商机"),'clues'=>__("线索")];
        $this->request->filter(['strip_tags']);
    }

    /**
     * 查看
     */
    public function index()
    {

        $source = $this->request->param('source', 'customer');
        if (!isset($this->modelList[$source])) {
            $this->error(__("错误类型"));
        }

        $condition = ['source' => $source];
        $prefix = \think\Config::get('database.prefix');
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($condition)
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($condition)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $fieldList = $this->getTableFields("{$prefix}facrm_{$source}",false);
            $list = collection($list)->toArray();
            $temp_arr = array_column($list, 'name');

            foreach ($fieldList as $field) {
                if (array_search($field['name'], $temp_arr) !== false) {
                    continue;
                }
                $item = [
                    'id' => $field['name'],
                    'state' => false,
                    'source' => '-',
                    'name' => $field['name'],
                    'title' => $field['title'],
                    'type' => $field['type'],
                    'issystem' => true,
                    'isfilter' => 0,
                    'islist' => 0,
                    'isorder' => 0,
                    'status' => 'normal',
                    'createtime' => 0,
                    'updatetime' => 0
                ];

                $list[] = $item;
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->assignconfig('params', "/source/{$source}");
        $this->assignconfig('source', $source);
        $this->view->assign('source', $source);
        $this->view->assign('modelList', $this->modelList);

        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {

        $source = $this->request->param('source');

        if (!isset($this->modelList[$source])) {
            $this->error(__("错误类型"));
        }
        $this->view->assign('source', $source);

        $this->renderTable();

        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $this->renderTable();
        return parent::edit($ids);
    }

    /**
     * 渲染表
     */
    protected function renderTable()
    {
        $tableList = [];
        $dbname = \think\Config::get('database.database');
        $list = \think\Db::query("SELECT `TABLE_NAME`,`TABLE_COMMENT` FROM `information_schema`.`TABLES` where `TABLE_SCHEMA` = '{$dbname}';");
        foreach ($list as $key => $row) {
            $tableList[$row['TABLE_NAME']] = $row['TABLE_COMMENT'];
        }
        $this->view->assign("tableList", $tableList);
    }

    /**
     * 批量操作
     * @param string $ids
     */
    public function multi($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        return parent::multi($ids);
    }


    /**
     * 获取表字段信息
     * @param string $table 表名
     * @return array
     * @internal
     */
    public function getTableFields($table="",$return_ajax=true)
    {
        if (!$table){
            $this->success(__("表名不能为空"));
        }
        $dbname = \config('database.database');
        //从数据库中获取表字段信息
        $sql = "SELECT * FROM `information_schema`.`columns` WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION";
        //加载主表的列
        $columnList = Db::query($sql, [$dbname, $table]);
        $fieldlist = [];
        foreach ($columnList as $index => $item) {
            $fieldlist[] = ['name' => $item['COLUMN_NAME'], 'title' => $item['COLUMN_COMMENT'], 'type' => $item['DATA_TYPE']];
        }
        if ($return_ajax){
            $this->success("", null, ['fieldList' => $fieldlist]);
        }
        return $fieldlist;
    }

    /**
     * 获取自定义字段
     * @internal
     */
    public function get_fields_html($source = "",$tpl = "fields")
    {
        $html="facrm/common/".$tpl;

        switch ($source) {
            case 'customer':
                $this->model = new \app\admin\model\facrm\Customer();
                break;
            case 'customer_contacts':
                $this->model =new \app\admin\model\facrm\customer\Contacts();
                break;
            case 'contract':
                $html="facrm/common/fields_4_12";
                $this->model = new \app\admin\model\facrm\Contract();
                break;
            case 'contract_receivables':
                $html="facrm/common/fields_4_12";
                $this->model = new \app\admin\model\facrm\contract\Receivables();
                break;
            case 'business':
                $html="facrm/common/fields_4_12";
                $this->model = new \app\admin\model\facrm\Business();
                break;
            case 'clues':
                $this->model = new \app\admin\model\facrm\Clues();
                break;
            default:
                $this->error();
        }
        $this->view->engine->layout(false);
        $id = $this->request->param('id', 0, 'intval');
        $values = [];

        if ($id > 0) {
            $values = $this->model->find($id);
        }
        $fields = \app\admin\model\facrm\Fields::getCustomFields($source, $values);

        $this->view->assign('fields', $fields);
        $this->view->assign('values', $values);
        $this->success('', null, ['html' => $this->view->fetch($html)]);
    }


    /**
     * 规则列表
     * @internal
     */
    public function rulelist()
    {
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $keyValue = $this->request->request("keyValue", "");

        $keyValueArr = array_filter(explode(',', $keyValue));
        $regexList = Config::getRegexList();
        $list = [];
        foreach ($regexList as $k => $v) {
            if ($keyValueArr) {
                if (in_array($k, $keyValueArr)) {
                    $list[] = ['id' => $k, 'name' => $v];
                }
            } else {
                $list[] = ['id' => $k, 'name' => $v];
            }
        }
        return json(['list' => $list]);
    }

    /**
     * 关联表联动
     * @internal
     */
    public function selectpage()
    {
        $id = $this->request->get("id/d", 0);
        $fieldInfo = $this->model::get($id);
        if (!$fieldInfo) {
            $this->error("未找到指定字段");
        }
        $setting = $fieldInfo['setting'];
        if (!$setting || !isset($setting['table'])) {
            $this->error("字段配置不正确");
        }
        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        //$field = $this->request->request("showField");
        $field = $setting['field'];
        //主键
        //$primarykey = $this->request->request("keyField");
        $primarykey = $setting['primarykey'];
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        $searchfield = [$field, $primarykey];
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        $custom = isset($setting['conditions']) ? (array)json_decode($setting['conditions'], true) : [];
        $custom = array_filter($custom);

        $admin_id = session('admin.id') ?: 0;
        $user_id = $this->auth->id ?: 0;
        //如果是管理员需要移除user_id筛选,否则会导致管理员无法筛选列表信息
        $admin = $this->request->request("admin/d");
        if ($admin_id && $admin) {
            unset($custom['user_id']);
        } else {
            //如果不是管理员则需要判断是否开放相应的投稿字段
            if (!in_array($fieldInfo['source'], array_keys($this->modelList))) {
                $this->error("未开放栏目信息");
            }
        }

        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 99999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $where = function ($query) use ($primaryvalue, $custom, $admin_id, $user_id) {
                $query->where('id', 'in', $primaryvalue);
                if ($custom && is_array($custom)) {
                    //替换暂位符
                    $search = ["{admin_id}", "{user_id}"];
                    $replace = [$admin_id, $user_id];
                    foreach ($custom as $k => $v) {

                        (is_array($v)&&json_decode($v))?$v=json_decode($v,true):'';

                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), str_replace($search, $replace, $v[1]));
                        } elseif (is_array($v) && 1 == count($v)){
                            $query->where($k,  key($v), str_replace($search, $replace, reset($v)));
                        } else {
                            $query->where($k, '=', str_replace($search, $replace, $v));
                        }
                    }
                }
            };
            $pagesize = 99999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom, $admin_id, $user_id) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $word = array_filter($word);
                if ($word) {
                    foreach ($word as $k => $v) {
                        $query->where(str_replace(',', $logic, $searchfield), "like", "%{$v}%");
                    }
                }
                if ($custom && is_array($custom)) {
                    //替换暂位符
                    $search = ["{admin_id}", "{user_id}"];
                    $replace = [$admin_id, $user_id];
                    foreach ($custom as $k => $v) {

                        if (!is_array($v)){
                            json_decode($v)?$v=json_decode($v,true):'';
                        }
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), str_replace($search, $replace, $v[1]));
                        } elseif (is_array($v) && 1 == count($v)){
                            $query->where($k,  key($v), str_replace($search, $replace, reset($v)));
                        }else {
                            $query->where($k, '=', str_replace($search, $replace, $v));
                        }
                    }
                }
            };
        }
        $list = [];
        $total = Db::table($setting['table'])->where($where)->count();
        if ($total > 0) {
            $datalist = Db::table($setting['table'])->where($where)
                ->order($order)
                ->page($page, $pagesize)
                ->field($primarykey . "," . $field . ($istree ? ",pid" : ""))
                ->select();
            foreach ($datalist as $index => &$item) {
                unset($item['password'], $item['salt']);
                $list[] = [
                    $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                    $field      => isset($item[$field]) ? $item[$field] : '',
                    'pid'       => isset($item['pid']) ? $item['pid'] : 0
                ];
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init($list, 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }


}
